<?php
namespace app\admin\model;
use think\Config;
use think\Db;
class UserModel extends \app\common\model\CommonModel
{

    /**
     * @param string $company    公司
     * @param string $username   用户姓名
     * @param int    $pagesize   页码大小
     * @param int    $page       页码
     * @return array
     */
    public function list($params)
    {
        try {
            $page     = isset($params['page']) && is_numeric($params['page']) ? (int)$params['page'] : 1;
            $pagesize = isset($params['pagesize']) && is_numeric($params['pagesize']) ? (int)$params['pagesize'] : 10;
            $start = ($page-1) * $pagesize;
            $field = "a.userid,a.username,a.company,a.post,a.mail,a.department,a.picnum,a.create_time,b.login_time";
            $sql = "SELECT {$field} FROM user a LEFT JOIN 
                    (SELECT userid,max(event_time) login_time FROM log where `event` = 'login' GROUP BY userid) b ON a.userid = b.userid WHERE 1=1 ";
            if(!empty($params['company'])){
                $sql .= "AND a.`company` = '{$params['company']}' ";
            }
            if(!empty($params['username'])){
                $sql .= "AND (a.`username` LIKE '%{$params['username']}%' OR a.`userid` LIKE '%{$params['username']}%') ";
            }
            $order = "ORDER BY a.create_time DESC LIMIT {$start},{$pagesize}";
            $csql = str_replace($field,'count(*)',$sql);
            $sql .= $order;
            $res = $this->getRes($sql);
            $count = $this->getCount($csql);
            return $this->pageData($res,$pagesize,$page,$count);
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
    
    /**
     * 编辑文生图次数
     * @param string    $userid
     * @param int       $num
     */
    public function edit_picture_num($userid,$num)
    {
        try {
            return Db::table('user')->where(['userid' => $userid])->update(['picnum' => $num]);
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
}